<!-- 农事任务管理页面 -->
<template>
  <BaseMainSlot :show-tab-box="true">
    <template v-slot:tab-box>
      <div class="tabBox">
        <label style="min-width: 70px; margin-left: 80px">作业名称:</label>
        <SelectButton
          @nowselectbuttonindex="workChange"
          @updateQueryAllList="updateQueryAllList"
        />
      </div>
    </template>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="30"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :has-edit="false"
        :has-save="false"
        :has-cancel="false"
        :has-edit-column="false"
        @showColumn="showColumn"
        @add="add"
        @cancel="cancel('formData')"
        @edit="edit"
        @del="del"
        @save="save('formData')"
      />
    </template>
    <template v-slot:search-box>
      <SearchForm
        :form-config="formConfig"
        :form-data="searchlist"
        @search="search"
      />
    </template>
    <template v-slot:table-box>
      <Table
        v-loading="loading"
        :prop-list="tableColumn"
        :list-data="tableData"
        @sortChange="changeTableSort"
        @handleSelectionChange="handleSelectionChange"
      >
        <template v-slot:svcObjPropertyList="{ row, item }">
          {{ getSvcObj(row, item.prop) }}
        </template>
        <template v-slot:operation="{ row }">
          <template v-if="!row.index && row.agriculturalTaskId">
            <el-button
              v-if="judgePermission(30, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="handleEdit(row)"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-if="judgePermission(30, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(row)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </template>
        <template v-slot:facilityBOList="{ row }">
          <template v-if="!row.index && row.agriculturalTaskId">
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="seeEquip(row)"
            >
              <i class="el-icon-view"></i> 查看
            </el-button>
          </template>
        </template>
        <!-- 查看农资 -->
        <template v-slot:inputsRecordBOList="{ row }">
          <template v-if="!row.index && row.agriculturalTaskId">
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="seeEquips(row)"
            >
              <i class="el-icon-view"></i> 查看
            </el-button>
          </template>
        </template>
        <template v-slot:execStartTime="{ row }">
          <template v-if="!row.index && row.agriculturalTaskId">
            {{ row.execStartTime }} - {{ row.execEndTime }}
          </template>
        </template>
        <template v-slot:personBOList="{ row }">
          <template v-if="!row.index && row.agriculturalTaskId">
            <span
              v-for="(facitem, facindex) in row.personBOList"
              :key="facindex"
            >
              <span v-if="facitem">
                {{ facitem.name }}
                <span v-if="facindex != row.personBOList.length - 1">、</span>
              </span>
            </span>
          </template>
        </template>
      </Table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="dialogTitle + '农事任务信息'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
      >
        <div class="form" style="margin-bottom: 10px">
          <el-form
            ref="formData"
            label-position="left"
            :model="formData"
            :rules="rules"
            class="el-form"
          >
            <el-form-item
              v-if="nowChanceStau === 'add'"
              label="批次名称:"
              prop="batchList"
              class="w100p"
            >
              <el-select
                v-model="formData.batchList"
                clearable
                multiple
                :multiple-limit="0"
                @change="batch"
              >
                <el-option
                  v-for="(item,index) in batchList"
                  :key="index"
                  :label="item.batchName"
                  :value="item.batchNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="nowChanceStau === 'edit'"
              label="批次名称:"
              prop="batchNo"
              class="w100p"
            >
              <el-select
                v-model="formData.batchNo"
                clearable
                disabled
              >
                <el-option
                  v-for="item in allBatchList"
                  :key="item.batchNo"
                  :label="item.batchName"
                  :value="item.batchNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              v-if="nowChanceStau === 'add'"
              label="设施选择:"
              prop="facilityNoList"
              class="w100p pointList"
            >
              <div style="width: 100%">
                <div
                  v-for="(data, index) in formData.batchList"
                  :key="index"
                  style="display: flex; margin-bottom: 10px"
                >
                  <div style="width: 120px; margin-right: 20px; flex-shrink: 0">
                    {{ productionBatchBOList[index].batchName }}
                  </div>
                  <div style="width: 100%">
                    <el-select
                      v-model="productionBatchBOList[index].facilityNoList"
                      style="width: 100%"
                      multiple
                      clearable
                    >
                      <el-option
                        v-for="(item, index3) in facilityAList[index]"
                        :key="index3"
                        :label="item.facilityName"
                        :value="item.facilityNo"
                      />
                    </el-select>
                  </div>
                </div>
              </div>
            </el-form-item>
            <el-form-item
              v-if="nowChanceStau === 'edit'"
              label="设施选择:"
              prop="facilityNoList"
              class="w100p pointList"
            >
              <div style="width: 100%">
                <div
                  v-for="(data, index) in 1"
                  :key="index"
                  style="display: flex; margin-bottom: 10px"
                >
                  <div style="width: 120px; margin-right: 20px; flex-shrink: 0">
                    {{ productionBatchBOList[index].batchName }}
                  </div>
                  <div style="width: 100%">
                    <el-select
                      v-model="facilityNoList"
                      style="width: 100%"
                      multiple
                      filterable
                      clearable
                      @change="$forceUpdate()"
                    >
                      <el-option
                        v-for="(item, ind) in facilityAList[index]"
                        :key="ind"
                        :label="item.facilityName"
                        :value="item.facilityNo"
                      />
                    </el-select>
                  </div>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="作业人:" class="w100p" prop="personNoList">
              <el-select
                v-model="formData.personNoList"
                clearable
                multiple
                @change="changePersonNoList"
              >
                <el-option
                  v-for="(item, index) in staffList"
                  :key="index"
                  :label="item.person.name"
                  :value="item.personNo"
                />
              </el-select>
            </el-form-item>
            <!-- 农资 -->
            <el-form-item
              v-for="(item, index) in materialNum"
              :key="index"
              style="
                position: relative;
                border: 1px dashed #00ffff;
                padding: 10px;
              "
              class="w100p"
            >
              <el-form-item label="投入农资" class="w33p">
                <el-select v-model="materialNos[index]" filterable clearable>
                  <el-option
                    v-for="(item, index) in agriculturalMaterialList"
                    :key="index"
                    :label="item.materialName"
                    :value="item.materialNo"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="投入量:" class="w50p">
                <el-input
                  v-model="assetQuantity[index]"
                  style="width: 70%"
                  type="number"
                  min="0"
                  @change="assetQuantity[index] < 0 && ($set(assetQuantity, index, 0))"
                  placeholder="请输入投入量"
                  clearable
                />
                <div
                  style="width: calc(30% - 10px); margin-left: 10px"
                  v-if="materialNos[index]"
                >
                  {{
                    agriculturalMaterialList.filter(
                      (el) => el.materialNo === materialNos[index]
                    )[0]
                      ? agriculturalMaterialList.filter(
                          (el) => el.materialNo === materialNos[index]
                        )[0].unitName
                      : undefined
                  }}
                </div>
              </el-form-item>
              <el-form-item label="经手人:" class="w50p" style="margin-top: 20px;">
                <el-select v-model="personNos[index]" clearable>
                    <el-option
                    v-for="(item, index) in staffList"
                    :key="index"
                    :label="item.person.name"
                    :value="item.personNo"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="换算量:"
                class="w100p"
                style="margin-top: 20px"
              >
                <el-input
                  v-model="exchangeRatio[index]"
                  style="width: 38%"
                  type="number"
                  placeholder="请输入换算量"
                  clearable
                />
                <el-select
                  v-model="exchangeUnitNo[index]"
                  filterable
                  style="width: 38%"
                  clearable
                >
                  <el-option
                    v-for="item in unitlists"
                    :key="item.unitNo"
                    :label="item.unitName"
                    :value="item.unitNo"
                  />
                </el-select>
              </el-form-item>
              <!-- 换算预览 -->
              <el-form-item
                label="换算预览:"
                class="w100p"
                v-if="
                  assetQuantity[index] &&
                  exchangeRatio[index] &&
                  exchangeUnitNo[index] &&
                  materialNos[index]
                "
                style="margin-top: 20px; display: flex"
              >
                <div>
                  <span v-if="assetQuantity[index] && exchangeRatio[index]">{{
                    (assetQuantity[index] / exchangeRatio[index]).toFixed(2)
                  }}</span>
                  <span v-if="materialNos[index] && exchangeUnitNo[index]">{{
                    agriculturalMaterialList.filter(
                      (el) => el.materialNo === materialNos[index]
                    )[0].unitName
                  }}</span>
                  <span v-if="exchangeUnitNo[index] && materialNos[index]"
                    >/{{
                      unitlists.filter(
                        (el) => el.unitNo === exchangeUnitNo[index]
                      )[0].unitName
                    }}</span
                  >
                </div>
                <div v-show="exchangeRatio[index]" style="margin-left: 10px">
                  <span v-if="exchangeRatio[index] && exchangeUnitNo[index]"
                    >总计：</span
                  >
                  <span v-if="exchangeRatio[index]">{{
                    exchangeRatio[index]
                  }}</span>
                  <span v-if="exchangeUnitNo[index]">
                    {{
                      unitlists.filter(
                        (el) => el.unitNo === exchangeUnitNo[index]
                      )[0].unitName
                    }}</span
                  >
                </div>
                <div v-show="assetQuantity[index]" style="margin-left: 10px">
                  <span v-if="assetQuantity[index] && materialNos[index]">
                    总重：</span
                  >
                  <span v-if="assetQuantity[index]">{{
                    assetQuantity[index]
                  }}</span>
                  <span v-if="materialNos[index]">{{
                    agriculturalMaterialList.filter(
                      (el) => el.materialNo === materialNos[index]
                    )[0].unitName
                  }}</span>
                </div>
              </el-form-item>
              <img
                v-show="index === 0"
                src="@/assets/add.png"
                style="position: absolute; bottom: 0; right: 0; cursor: pointer"
                @click="addMaterial"
              />
              <img
                src="@/assets/reduce.png"
                alt=""
                style="position: absolute; top: 8px; right: 0; cursor: pointer"
                v-if="index > 0"
                @click="reduce(index)"
              />
            </el-form-item>
            <el-form-item class="w50p" label="执行时间:" prop="execStartTime">
              <el-date-picker
                v-model="formData.execStartTime"
                type="datetime"
                value-format="timestamp"
                placeholder="请选择开始时间"
              />
            </el-form-item>
            <div style="padding: 0 7px">~</div>
            <el-form-item class="w50p" prop="execEndTime">
              <el-date-picker
                v-model="formData.execEndTime"
                type="datetime"
                value-format="timestamp"
                placeholder="请选择结束时间"
                style="width: calc(100% - 132px)"
              />
            </el-form-item>
            <el-form-item
              label="通知时间:"
              prop="noticeTime"
              class="w50p pointList"
            >
              <el-date-picker
                v-model="formData.noticeTime"
                type="datetime"
                value-format="timestamp"
                placeholder="请选择通知时间"
              />
            </el-form-item>
            <el-form-item
              v-for="item in svcData"
              :key="item.propertyCode"
              :prop="item.propertyCode"
              :label="`${item.propertyName}:`"
              :rules="item.required ? [{
                required: true,
                message: `${item.propertyName}不能为空`,
                trigger: ['change', 'blur'],
              }] : []"
              class="w50p"
            >
              <el-input
                v-if="item.propertyType == 1"
                v-model="formData[item.propertyCode]"
                :placeholder="`请输入${item.propertyName}`"
                clearable
              />
              <el-input
                v-if="item.propertyType == 2"
                v-model="formData[item.propertyCode]"
                type="number"
                :placeholder="`请输入${item.propertyName}`"
                clearable
              />
              <el-date-picker
                v-if="item.propertyType == 4"
                v-model="formData[item.propertyCode]"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                :placeholder="`请选择${item.propertyName}`"
              />
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')"
            >取 消</el-button
          >
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
            >保 存</el-button
          >
        </div>
      </el-dialog>
      <el-dialog
        id="tableColumnDialog"
        title="配置列"
        :visible.sync="dialogTableColumnVisible"
      >
        <tableColumn
          v-if="dialogTableColumnVisible"
          ref="tableColumn"
          :table-column="allTableColumn"
          @cancelColumn="cancelColumn"
        />
        <div slot="footer" class="dialog-footer">
          <el-button
            class="zh-button-one"
            @click="dialogTableColumnVisible = false"
          >
            取 消
          </el-button>
          <el-button class="zh-button-two" type="primary" @click="saveColumn">
            保 存
          </el-button>
        </div>
      </el-dialog>
      <SeeEquip
        :is-show-equip="isShowEquip"
        :equip-data="facilityBOList"
        @closeDialog="isShowEquip = false"
      />
      <el-dialog
        title="投入农资信息"
        :visible.sync="showEquips"
        width="30%"
        class="dialogRec"
        @close="showEquips = false"
      >
        <div class="facility-list">
          <div
            v-for="(item, index) in inputsRecordBOList"
            :key="index"
            class="facility-item"
          >
            <!-- {{ item.facilityName }} -->
            <div class="info-line">
              <div class="name">投入农资名称：</div>
              <div class="value">{{ item.materialDTO.materialName }}</div>
            </div>
            <div class="info-line">
              <div class="name">投入量：</div>
              <div class="value">{{ item.assetQuantity }}</div>
            </div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="showEquips = false"
            >关 闭</el-button
          >
        </span>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import SearchForm from "@/components/searchForm";
import Table from "@/components/table/table.vue";
import SeeEquip from "@/components/seeEquip/index.vue";
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import axios from "axios";
import SelectButton from "@/components/selectbutton/index1.vue";
// 获取下拉框
import agriculturalRecords from "@/api/digital-production/agricultural-work-management/agricultural-records-management";
import managementtwo from "@/api/digital-production/agr-input-management/agr-input-managementtwo";
import classificat from "@/api/digital-production/agricultural-work-management/agricultural-work-classification";
import nowstaff from "@/api/digital-operation/personnel-cost-mansge/staff-manage/index";
import nowpagereq from "@/api/basic-info-manage/agr-source-base-Manage/index";
import danwei from "@/api/basic-info-manage/unit-manage/index";
import userreq from "@/api/user/index";
import { mymixin } from "@/utils/mixin";
import moment from "moment";
import { getToken } from "@/utils/auth";
import { mapGetters } from "vuex";
import { propertyTime, propertyTimeJoin } from "@/utils/time";
export default {
  name: "AgriculturalTaskManagement",
  components: {
    SearchForm,
    Table,
    Pagination,
    BaseMainSlot,
    ActionBar,
    SeeEquip,
    SelectButton,
  },
  mixins: [mymixin],
  data() {
    return {
      tableColumn: [],
      tableColumn1: [
        { prop: "batchName", label: "批次名称", minWidth: "140" },
        { prop: "batchNo", label: "批次号" },
        {
          prop: "facilityBOList",
          label: "设施名称",
          slotName: "facilityBOList",
        },
        {
          prop: "inputsRecordBOList",
          label: "投入农资",
          slotName: "inputsRecordBOList",
        },
        { prop: "personBOList", label: "执行人", slotName: "personBOList" },
        {
          prop: "execStartTime",
          label: "执行时间",
          slotName: "execStartTime",
          width: "320",
        },
        {
          prop: "operation",
          label: "操作",
          slotName: "operation",
          width: "120",
        },
      ],
      formConfig: [
        {
          label: "选择批次",
          prop: "batchNo",
          type: "select",
          options: [],
          optionKey: { label: "batchName", value: "batchNo" },
        },
        {
          label: "选择设施",
          prop: "facilityNo",
          type: "select",
          options: [], // facilityList
          optionKey: { label: "facilityName", value: "facilityNo" },
        },
        {
          label: "作业名称",
          prop: "agriculturalWorkTypeNo",
          type: "select",
          options: [], // queryAllList
          optionKey: {
            label: "agriculturalWorkTypeName",
            value: "agriculturalWorkTypeNo",
          },
        },
        {
          label: "农资名称",
          prop: "materialNo",
          type: "select",
          options: [], // queryagriculturalMaterialList
          optionKey: { label: "materialName", value: "materialNo" },
        },
        {
          label: "执行人",
          prop: "personNo",
          type: "select",
          options: [], // StaffList
          optionKey: { label: "personName", value: "personNo" },
        },
        {
          label: "选择时间",
          prop: "date",
          type: "daterange",
        },
      ],
      allBatchList: [],
      batchList: [],
      formData: {
        agriculturalWorkTypeName: " ",
        batchNo: "",
        facilityNoList: [],
        agriculturalMaterialId: "",
        investmentVolume: "",
        unitNo: "",
        loss: "",
        agriculturalMachineryId: "",
        employeeId: "",
        noticeTime: "",
        execStartTime: "",
        execEndTime: "",
        inputsRecordBOList: [],
        workloadUnitNo: null,
        personNoList: [],
        batchSingleNos: [],
      },
      singleNoList: [],
      activeSingleNoList: [],
      materialNum: 1,
      materialNos: [],
      exchangeRatio: [],
      exchangeUnitNo: [],
      assetQuantity: [],
      personNos: [],
      showEquips: false,
      showIdNameList: false,
      logoImg: require("@/assets/logo.png"),
      //  标签栏相关
      activeName: "first",
      // ----上传图片相关---
      // 图片地址
      imageurl: "",
      // ---end---
      // 投入类型列表
      inputTypeList: [],
      routeName: "",
      // 当前页
      installationName: "",
      // 选中的设施id数组 ID组成
      incomeCostIdList: [],
      // 柱状图相关值
      bottomtabdat: {},
      tabtype: false,
      agriculturalWorkType: {},
      facilityVoList: [],
      scope: "",
      // 批次名称Id
      batchNo: undefined,
      // 设施
      facilityAList: [],
      queryagriculturalMaterialList: [],
      StaffList: [],
      materialNo: "",
      personNo: "",
      // 设施Id
      facilityNo: undefined,
      // 农资
      AgriculturalList: [],
      agriculturalWorkTypeNo: "",
      agriculturalWorkTypeName: "",
      // 搜索时间
      searchlist: {},
      tagsList: [],
      // 农事作业
      queryAllList: [],
      unitlistOfWorkload: [],
      unitlistOfAsset: [],
      agriculturalMaterialList: [],
      // 判断是否有农资损耗
      waste: "",
      facilityNoList: [],
      batchSingleNos: [],
      // 人员
      staffList: [],
      queryEquipmentList: [],
      dialogTitle: "",
      dialogFormVisible: false,
      inputsRecordBOList: [],
      facilityAListEdit: [],
      // 部门岗位员工列表
      departmentList: [],
      postList: [],
      productionBatchBOList: [],
      facilityBOList: [],
      isShowEquip: false,
      unitlists: [],
      rules: {
        employeeId: [
          { required: true, message: "请选择执行人", trigger: "change" },
        ],
        agriculturalWorkTypeName: [
          { required: true, message: "请输入农事作业类型", trigger: "blur" },
        ],
        workload: [
          { required: true, message: "请输入作业量", trigger: "blur" },
        ],
        batchList: [
          {
            required: true,
            message: "请选择批次",
            trigger: ["change", "blur"],
          },
        ],
        batchNo: [
          {
            required: true,
            message: "请选择批次",
            trigger: ["change", "blur"],
          },
        ],
        batchSingleNos: [
          {
            required: true,
            message: "编号不能为空",
            trigger: ["change", "blur"],
          },
        ],
        noticeTime: [
          {
            required: true,
            message: "请选择通知时间",
            trigger: ["change", "blur"],
          },
        ],
        personNoList: [
          { required: true, message: "执行人不能为空", trigger: "change" },
        ],
        execStartTime: [
          { required: true, message: "请选择执行开始时间", trigger: "change" },
        ],
        execEndTime: [
          { required: true, message: "请选择执行结束时间", trigger: "change" },
        ],
      },
      svcData: [],
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  created() {
    this.tableColumn = [ ...this.tableColumn1 ]
    this.zhnewgetqueryAllList();
    this.getqueryAllList();
  },
  mounted() {
    this.getStaffList();
  },
  methods: {
    changePersonNoList(e) {
      this.$forceUpdate()
      if(this.materialNum>0) {
        for(let i=0;i<this.materialNum;i++){
          if(!this.personNos[i]) {
            this.personNos[i] = e[0]
          }
        }
      }
    },
    // 获取表格数据
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        sortList: this.sortList || [],
        entity: {
          // taskType: "临时任务",
          batchNo: this.searchlist.batchNo || undefined,
          farmingTypeNo: sessionStorage.farmingTypeNo,
          agriculturalWorkTypeNo: this.agriculturalWorkTypeNo,
          facilityNo: this.searchlist.facilityNo || undefined,
          startTime: this.searchlist.date && this.searchlist.date[0],
          endTime: this.searchlist.date && this.searchlist.date[1],
          materialNo: this.searchlist.materialNo || undefined,
          personNo: this.searchlist.personNo || undefined,
        },
      };
      params.entity["batchType"] = "BATCH";
      this.entity = params.entity;
      if (this.agriculturalWorkTypeNo) {
        agriculturalRecords.getCulturalList(params).then((res) => {
          this.loading = false;
          let data = res.data;
          this.totalSize = data.totalElements;
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
        });
      }
    },
    getStaffList(no) {
      managementtwo.getEmployeeList(no).then((res) => {
        if (res.code !== 1) {
          return;
        }
        this.staffList = res.data;
      });
    },
    // 获取作业方式
    getqueryAllList() {
      // 获取单位选择框数据
      danwei
        .getallunitlist({ unitTypeNo: "995416636939862016" })
        .then((res) => {
          this.unitlistOfWorkload = res.data;
        });
      danwei
        .getallunitlist({ unitTypeNo: "1001491616960118784" })
        .then((res) => {
          this.unitlistOfAsset = res.data;
        });
      danwei
        .getallunitlist({
          unitTypeNo: "995416607651037184",
          organizationNo: sessionStorage.organizationNo,
        })
        .then((res) => {
          this.unitlists = res.data;
        });
      nowstaff.getStaffListByCondition().then((res) => {
        this.StaffList = res.data;
        this.formConfig[4].options = res.data.map((el) => {
          return { ...el, personName: el.person?.name };
        });
      });
      let param = {};
      param = {
        farmingTypeNo: sessionStorage.farmingTypeNo,
        status: 0,
        batchType: "BATCH",
      };
      // 获取批次选择框数据
      managementtwo.queryBatchList(param).then((res) => {
        this.batchList = res.data;
        this.formConfig[0].options = res.data;
      });
      // 获取批次选择框数据
      managementtwo.queryBatchList({
        farmingTypeNo: sessionStorage.farmingTypeNo,
        batchType: "BATCH",
      }).then((res) => {
        this.allBatchList = res.data;
      });
      let params = {};
      if (this.nowChanceStau === "add") {
        params = {
          organizationList: sessionStorage
            .getItem("organizationList")
            .split(","),
          farmingTypeNo: sessionStorage.getItem("farmingTypeNo"),
          facilityStatus: 1,
        };
      } else {
        params = {
          organizationList: sessionStorage
            .getItem("organizationList")
            .split(",")
            .concat([sessionStorage.parentId || ""]),
          farmingTypeNo: sessionStorage.getItem("farmingTypeNo"),
        };
      }
      userreq.getfacilityAll(params).then((res) => {
        this.formConfig[1].options = res.data;
        this.facilityAList = res.data;
        this.facilityAListEdit = res.data;
      });
      managementtwo.getqueryList().then((res) => {
        this.queryagriculturalMaterialList = res.data;
        this.formConfig[3].options = res.data;
      });
      nowpagereq.getqueryList().then((res) => {
        let data = res.data;
        // 赋值总条数
        // this.totalSize = data.totalElements;
        // 赋值数组
        this.agriculturalMaterialList = data;
      });
    },
    // 获取农事作业名称
    zhnewgetqueryAllList() {
      if (getToken("parentId")) {
        let zhurl =
          this.$baseurl.webServiceUrl +
          "productionv2/agriculturalWorkType/queryByCondition";
        let neworglist =
          JSON.parse(getToken("organizationList")) + "," + getToken("parentId");
        axios({
          headers: {
            sysDataBaseName: sessionStorage.databaseName,
            accessToken: getToken("token"),
            systemMark: "MC",
            databaseName: getToken("databaseName"),
            organizationList: neworglist,
            organizationNo: JSON.stringify(getToken("organizationNo")),
          },
          data: {
            farmingTypeNo: getToken("farmingTypeNo"),
          },
          method: "post",
          url: zhurl,
        }).then((res) => {
          let data = res.data.data;
          this.queryAllList = data;
          if (data.length > 0) {
            this.agriculturalWorkTypeName = data[0].agriculturalWorkTypeName;
            this.agriculturalWorkTypeNo = data[0].agriculturalWorkTypeNo;
            this.getTableDataList();
          }
          this.queryAllList.forEach((el) => {
            el["name"] = el.agriculturalWorkTypeName;
          });
          this.agriculturalWorkTypeNo = res.data[0].agriculturalWorkTypeNo;
          this.formConfig[2].options = data;
        });
      } else {
        classificat.getqueryAllList().then((res) => {
          let data = res.data;
          this.queryAllList = data;
          if (data.length > 0) {
            this.agriculturalWorkTypeName = data[0].agriculturalWorkTypeName;
            this.agriculturalWorkTypeNo = data[0].agriculturalWorkTypeNo;
            this.getTableDataList();
          }
          this.queryAllList.forEach((el) => {
            el["name"] = el.agriculturalWorkTypeName;
          });
          this.agriculturalWorkTypeNo = res.data[0].agriculturalWorkTypeNo;
          this.formConfig[2].options = data;
        });
      }
      this.getTableDataList();
    },
    async batch(val) {
      if (val) {
        this.facilityAList = [];
        this.productionBatchBOList = [];
        let value = 0;
        val.forEach((item, index) => {
          let obj = this.batchList.find((el) => el.batchNo === item);
          value += obj.area;
          this.$set(this.facilityAList, index, obj.batchFacilityMapperList);
          this.$set(this.formData, "workloadUnitNo", obj.areaUnitNo);
          this.$set(this.productionBatchBOList, index, {
            batchNo: obj.batchNo,
            batchName: obj.batchName,
            facilityNoList: [],
          });
        });
        // 此处workload和作业量单位不可去掉
        this.$set(this.formData, "workload", JSON.parse(value.toFixed(2)));
      }
    },
    async batchs(e) {
      this.productionBatchBOList = [];
      this.facilityAList = [];
      this.formData.batchNo = e;
      this.productionBatchBOList = this.batchList.filter(
        (el) => el.batchNo === e
      );
      this.batchList
        .filter((el) => el.batchNo === e)
        .forEach((ell) => {
          this.facilityAList.push(ell.batchFacilityMapperList);
        });
      this.$set(this, "facilityNoList", []);
    },
    // 添加
    add() {
      this.openDialog("add");
      this.addActive = false;
      this.delActive = false;
      this.inputsRecordBOList = [];
      this.assetQuantity = [];
      this.personNos = []
      this.materialNos = [];
      this.singleNoList = [];
      this.activeSingleNoList = [];
      this.formData = {
        agriculturalWorkTypeName: this.agriculturalWorkTypeName,
        agriculturalWorkTypeNo: this.agriculturalWorkTypeNo,
      };
      this.inputsRecordBOList = [];
      this.assetQuantity = [];
      this.materialNos = [];
      this.exchangeRatio = [];
      this.exchangeUnitNo = [];
      this.$nextTick(() => {
        this.formData = { ...this.formData };
        this.$refs.formData.resetFields();
      });
    },
    cancel() {
      this.addActive = true;
      this.materialNum = 1;
      this.materialNos = [];
      this.exchangeRatio = [];
      this.exchangeUnitNo = [];
      this.assetQuantity = [];
      this.personNos = []
      this.formData = {};
      this.formData.personNoList = [];
      this.closeDialog();
      this.$nextTick(() => {
        this.$refs["formData"].clearValidate();
      });
    },
    // 修改
    async handleEdit(row) {
      this.svcObjPropertyList = row.svcObjPropertyList || []
      this.formData = { ...row };
      this.facilityAList = [];
      this.productionBatchBOList = [];
      this.formData.batchNo = row.batchNo;
      this.productionBatchBOList.push({
        batchNo: row.batchNo,
        batchName: row.batchName,
        facilityNoList: [],
      });
      this.batchList
        .filter((el) => el.batchNo === row.batchNo)
        .forEach((ell) => {
          this.facilityAList.push(ell.batchFacilityMapperList);
        });
      this.facilityNoList = [];
      row.facilityBOList && row.facilityBOList.forEach((el) => {
        this.facilityNoList.push(el.facilityNo);
      });
      this.materialNos = [];
      this.assetQuantity = [];
      this.personNos = []
      this.exchangeRatio = [];
      this.exchangeUnitNo = [];
      if (row.inputsRecordBOList) {
        this.materialNum = row.inputsRecordBOList.length;
        row.inputsRecordBOList.forEach((el) => {
          this.materialNos.push(el.materialNo);
          this.assetQuantity.push(el.assetQuantity);
          this.personNos.push(el.personNo)
          this.exchangeRatio.push(el.exchangeRatio);
          this.exchangeUnitNo.push(el.exchangeUnitNo);
        });
      }
      // 执行人
      this.$set(this.formData, "personNoList", []);
      row.personBOList.forEach((el, index) => {
        this.$set(this.formData.personNoList, index, el.personNo);
      });
      // 时间
      this.$set(
        this.formData,
        "execEndTime",
        JSON.parse(JSON.stringify(new Date(row.execEndTime).getTime()))
      );
      this.$set(
        this.formData,
        "execStartTime",
        JSON.parse(JSON.stringify(new Date(row.execStartTime).getTime()))
      );
      this.$set(
        this.formData,
        "noticeTime",
        JSON.parse(JSON.stringify(new Date(row.noticeTime).getTime()))
      );
      this.batchSingleNos = [];
      if (row.singleMappers) {
        row.singleMappers.forEach((el) => {
          this.batchSingleNos.push(el.singleNo);
        });
      }
      // 自定义字段
      if (row.svcObjPropertyList && this.svcData) {
        this.svcData && this.svcData.map(el => {
          let val = this.getSvcObj(row, el.propertyCode)
          // if (el.propertyType == 4) {
          //   val = propertyTimeJoin(val)
          // }
          this.$set(this.formData, el.propertyCode, val)
        })
      }
      this.openDialog("edit");
    },
    save(formData) {
      this.$refs[formData].validate((valid) => {
        if (valid) {
          if (this.nowChanceStau === "add") {
            let parone = {
              ...this.formData,
              organizationNo: sessionStorage.getItem("organizationNo"),
              personList: this.staffList.filter((item) =>
                this.formData.personNoList.includes(item.personNo)
              ),
              inputsRecordBOList: this.inputsRecordBOList,
              productionBatchBOList: this.productionBatchBOList,
            };
            parone.inputsRecordBOList = [];
            this.assetQuantity.forEach((el, index) => {
              parone.inputsRecordBOList.push({
                assetQuantity: el || null,
                personNo: this.personNos[index],
                materialNo: this.materialNos[index] || null,
                exchangeRatio: this.exchangeRatio[index] || null,
                exchangeUnitNo: this.exchangeUnitNo[index] || null,
                organizationNo:
                  sessionStorage.getItem("organizationNo") || null,
              });
            });
            // 判断设施是否为空
            let flag = parone.productionBatchBOList.every((el) =>
              el.facilityNoList.some((ell) => ell !== "")
            );
            if (!flag) {
              this.$message.warning("请选择设施，设施不能为空！");
              return;
            }
            parone["agriculturalWorkTypeName"] = this.agriculturalWorkTypeName;
            parone["agriculturalWorkTypeNo"] = this.agriculturalWorkTypeNo;
            // 自定义字段
            if (this.svcData) {
              let svcObjPropertyList = []
              this.svcData.map(el => {
                let obj = { ...el }
                let val = el.propertyType == 2 ? 'numValue' : 'textValue'
                obj[val] = parone[el.propertyCode]
                if (el.propertyType == 4) {
                  obj[val] = propertyTime(obj[val])
                }
                svcObjPropertyList.push(obj)
              })
              parone.svcClassId = this.svcData[0].svcClassId
              parone.svcObjPropertyList = svcObjPropertyList
            }
            
            agriculturalRecords.addMappermeslist(parone).then((res) => {
              if (res.code === 1) {
                this.batchNo = "";
                this.getTableDataList();
                this.closeDialog();
                this.$message.success("添加成功");
              } else {
                this.$message.error("添加失败");
              }
            });
          } else {
            this.formData.inputsRecordBOList = [];
            this.materialNos.forEach((el, index) => {
              this.formData.inputsRecordBOList.push({
                materialNo: el || null,
                assetQuantity: this.assetQuantity[index] || null,
                personNo: this.personNos[index],
                exchangeRatio: this.exchangeRatio[index] || null,
                exchangeUnitNo: this.exchangeUnitNo[index] || null,
                organizationNo:
                  sessionStorage.getItem("organizationNo") || null,
              });
            });
            this.$set(this.formData, "facilityNoList", this.facilityNoList);
            this.formData.personList = this.staffList.filter((el) => {
              return this.formData.personNoList.includes(el.personNo);
            });
            this.formData.facilityBOList = [];
            this.facilityNoList.forEach((el) => {
              this.facilityAListEdit.forEach((ell) => {
                if (el === ell.facilityNo) {
                  if (!this.formData.facilityBOList.includes(ell)) {
                    this.formData.facilityBOList.push(ell);
                  }
                }
              });
            });
            let params = { ...this.formData };
            // 自定义字段
            if (this.svcData) {
              let svcObjPropertyList = []
              this.svcData.map(el => {
                let obj = { ...el }
                let val = el.propertyType == 2 ? 'numValue' : 'textValue'
                obj[val] = params[el.propertyCode]
                if (el.propertyType == 4) {
                  obj[val] = propertyTime(obj[val])
                }
                obj.svcObjId = this.svcObjPropertyList[0].svcObjId
                let svcObj = this.svcObjPropertyList.find(ele => { return ele.propertyCode == el.propertyCode })
                svcObj && (obj.id = svcObj.id)
                svcObjPropertyList.push(obj)
              })
              params.svcClassId = this.svcData[0].svcClassId
              params.svcObjPropertyList = svcObjPropertyList
            }
            // 批量修改
            agriculturalRecords.editmeslist(params).then((res) => {
              if (res.code === 1) {
                this.closeDialog();
                this.batchNo = "";
                this.getTableDataList();
                this.$message.success("修改成功");
              } else {
                this.$message.error("修改失败");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    // 批量删除
    handleSelectionChange(list) {
      this.agriculturalTaskIdList = [];
      this.agriculturalTaskIdList = list.map((item) => item.agriculturalTaskNo);
      if (this.agriculturalTaskIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      if (this.nowChanceStau === "del") {
        let params = {
          noList: this.agriculturalTaskIdList,
        };
        agriculturalRecords.delmeslist(params).then((res) => {
          if (res.code === 1) {
            this.getTableDataList();
            this.$message.success("删除成功");
          } else {
            this.$message.error("删除失败");
          }
        });
      }
    },
    handleDelete(data) {
      let params = {
        noList: [data.agriculturalTaskNo],
      };
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          agriculturalRecords.delmeslist(params).then((res) => {
            if (res.code === 1) {
              this.$message.success("删除成功");
              this.getTableDataList();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          //
          this.$message("取消删除");
        });
    },
    getSvcObj(data, prop) {
      let val = ''
      if (data.svcObjPropertyList) {
        let row = data.svcObjPropertyList.find(el => {
          return el.propertyCode == prop
        })
        if (row) {
          val = row.textValue || row.numValue || ''
          if (row.propertyType == 4 && val) {
            val = propertyTimeJoin(val)
          }
        }
      }
      return val
    },
    // TODO:作业类型切换
    workChange(data) {
      if (this.queryAllList.length > 0) {
        this.agriculturalWorkTypeName = data.agriculturalWorkTypeName;
        this.agriculturalWorkTypeNo = data.agriculturalWorkTypeNo;
        this.svcData = data.svcData ? data.svcData.classPropertyList : [];
        if (this.svcData) {
          let tableColumn = [ ...this.tableColumn1 ]
          tableColumn.splice(tableColumn.length - 1)
          this.svcData && this.svcData.map(el => {
            tableColumn.push({
              prop: el.propertyCode,
              label: el.propertyName,
              slotName: "svcObjPropertyList",
              width: "110",
            })
          })
          // 表格列
          tableColumn.push({
            prop: "operation",
            label: "操作",
            slotName: "operation",
            width: "120",
          })
          this.tableColumn = [...tableColumn]
        } else {
          this.tableColumn = [ ...this.tableColumn1 ]
        }
      }
      if (this.agriculturalWorkTypeNo) {
        this.getTableDataList();
      }
    },
    updateQueryAllList(list) {
      this.queryAllList = list
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    // 时间格式
    dateFormat(row, colnum) {
      if (this.formData.agriculturalTaskId) {
        return moment(row[colnum.property]).format("YYYY-MM-DD");
      }
    },
     // 添加农资
     addMaterial() {
      this.materialNum++;
      for(let i=1;i<this.materialNum;i++){
          if(!this.personNos[i]) {
            this.personNos[i] = this.formData.personNoList[0]
          }
        }
    },
    reduce(index) {
      this.materialNum--;
      this.materialNos.splice(index, 1);
      this.assetQuantity.splice(index, 1);
      this.personNos.splice(index,1)
      this.exchangeRatio.splice(index, 1);
      this.exchangeUnitNo.splice(index, 1);
    },
    // 查看农资
    seeEquips(row) {
      this.inputsRecordBOList = row.inputsRecordBOList;
      this.showEquips = true;
    },
    // 查看设施
    seeEquip(row) {
      this.facilityBOList = row.facilityBOList;
      this.isShowEquip = true;
    },
  },
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";

::v-deep .el-dialog {
  .el-dialog__header .el-dialog__title {
    color: #fff;
  }

  background-color: #005d7b;
  border: #23fff8 1px solid;

  .el-form {
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
    justify-content: space-between;

    .el-form-item {
      display: flex;

      .el-form-item__label {
        min-width: 120px;
        text-align: end;
      }

      .el-input__inner {
        border: none;
      }
    }
  }
}

::v-deep .common-layout {
  overflow-y: auto;

  .search-box {
    .label-input {
      margin-bottom: 10px;

      .label {
        text-align: end;
        padding-right: 10px;
      }
    }

    flex-wrap: wrap;

    .el-date-editor.el-input {
      width: 200px;
    }

    .date {
      display: flex;

      .date-ps {
        display: block;
        height: 36px;
        line-height: 36px;
        padding: 0 10px;
      }
    }
  }

  .table {
    height: calc(100% - 310px);
    overflow: hidden;
    position: relative;
    padding-bottom: 40px;
  }
}

.content {
  height: 400px;
  display: flex;
  overflow-y: auto;
  justify-content: space-between;

  .left-box {
    width: 320px;
    height: 100%;
    padding: 10px;
    border: 1px solid #006e91;
    overflow-y: auto;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    flex-wrap: wrap;
    align-content: flex-start;

    .el-button {
      margin: 0;
      width: 140px !important;
      color: #ffffff;
      background-color: transparent;
      border: 1px solid #00ffff;
      white-space: nowrap;
      margin-right: 5px;
      margin-bottom: 10px;
      background: #006e91;
    }

    .el-button:hover {
      background-color: #01ffff;
      color: #001f30;
    }

    .el-button-click {
      background-color: #01ffff;
      color: #001f30;
    }
  }

  .right-box {
    width: calc(100% - 340px);
    height: 100%;
    overflow-y: auto;
    padding: 10px;
    border: 1px solid #006e91;

    .el-form {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      justify-content: space-between;
    }

    ::v-deep .el-form-item__label {
      width: 120px;
    }

    ::v-deep .el-form-item__content {
      display: flex;
    }
  }
}

.inputs-list {
  width: 100%;

  .input-item {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    border: 1px dashed #00ffff;
    padding: 12px;
    margin-top: 12px;

    .input-item-line {
      width: calc(33% - 20px);
      margin-bottom: 10px;

      &:not(:nth-child(3n)) {
        margin-right: 30px;
      }
    }
  }
}

// TODO:
.tabBox {
  display: flex;
  max-height: 45px;
  width: 100%;
  padding-bottom: 10px;
  overflow: hidden;
  overflow-x: auto;
  scroll-margin-top: 50px;

  &::-webkit-scrollbar {
    width: 10px;
    height: 5px;
    border-radius: 10px;
  }
}
// TODO: 查看投入物资
.facility-list {
  display: flex;
  justify-content: flex-start;
  flex-direction: row;
  flex-wrap: wrap;
  .facility-item {
    width: 400px;
    max-width: 30%;
    min-width: 30%;
    margin-right: 3%;
    margin-bottom: 10px;
    // height: 80px;
    border-radius: 5px;
    // border: 1px solid #ccc;
    box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.15);
    padding: 10px 20px;

    .info-line {
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
      font-size: 14px;
      &:not(:last-child) {
        margin-bottom: 10px;
      }
      .name {
        text-align: left;
        width: 100px;
        flex-shrink: 0;
      }
      .value {
        width: 100%;
        text-align: left;
        font-weight: normal;
      }
    }
  }
}
</style>
